package com.zhuiyi.zhxy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhuiyi.zhxy.pojo.Admin;
import com.zhuiyi.zhxy.pojo.LoginForm;
import com.zhuiyi.zhxy.pojo.Student;
import com.zhuiyi.zhxy.pojo.Teacher;
import com.zhuiyi.zhxy.service.AdminService;
import com.zhuiyi.zhxy.service.StudentService;
import com.zhuiyi.zhxy.service.TeacherService;
import com.zhuiyi.zhxy.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Description:
 * @Author: zhuiyi
 * @CreatTime: 2023/1/22 21:12
 **/
@Api(tags = "系统通用管理器")
@RestController
@RequestMapping("/sms/system")
public class SystemController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private StudentService studentService;


    //Request URL: http://localhost:9001/sms/system/updatePwd/admin/123456
    //Request Method: POST
    @ApiOperation("修改密码")
    @PostMapping("/updatePwd/{oldPwd}/{newPwd}")
    public Result updatePwd(
            @ApiParam("token口令")@RequestHeader("token") String token,
            @ApiParam("旧密码")@PathVariable("oldPwd") String oldPwd,
            @ApiParam("新密码")@PathVariable("newPwd") String newPwd
    ) {
        //判断token是否过期
        boolean expiration = JwtHelper.isExpiration(token);
        if (expiration) {
            return Result.build(null, ResultCodeEnum.TOKEN_ERROR);
        }
        //从token中解密出用户id和用户类型
        Long userId = JwtHelper.getUserId(token);
        Integer userType = JwtHelper.getUserType(token);
        oldPwd = MD5.encrypt(oldPwd);
        newPwd = MD5.encrypt(newPwd);
        //根据不同的用户类型去不同的表中找是否存在，该id的用户
        switch (userType) {
            case 1:
                QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
                adminQueryWrapper.eq("id", userId.intValue());
                adminQueryWrapper.eq("password", oldPwd);
                Admin admin = adminService.getOne(adminQueryWrapper);
                if (null != admin) {
                    //修改密码
                    admin.setPassword(newPwd);
                    adminService.saveOrUpdate(admin);
                }else {
                    //没找到提示用户旧密码有误
                    return Result.fail().message("原密码有误！");
                }
                break;
            case 2:
                QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
                studentQueryWrapper.eq("id", userId.intValue());
                studentQueryWrapper.eq("password", oldPwd);
                Student student = studentService.getOne(studentQueryWrapper);
                if (null != student) {
                    //修改密码
                    student.setPassword(newPwd);
                    //保存数据库
                    studentService.saveOrUpdate(student);
                }else {
                    //没找到提示用户旧密码有误
                    return Result.fail().message("原密码有误！");
                }
                break;
            case 3:
                QueryWrapper<Teacher> teacherQueryWrapper = new QueryWrapper<>();
                teacherQueryWrapper.eq("id", userId.intValue());
                teacherQueryWrapper.eq("password", oldPwd);
                Teacher teacher = teacherService.getOne(teacherQueryWrapper);
                if (null != teacher) {
                    //修改密码
                    teacher.setPassword(newPwd);
                    teacherService.saveOrUpdate(teacher);
                }else {
                    //没找到提示用户旧密码有误
                    return Result.fail().message("原密码有误！");
                }
                break;
        }
        return Result.ok();
    }



    ///sms/system/headerImgUpload
    @ApiOperation("文件上传统一接口")
    @PostMapping("/headerImgUpload")
    public Result headerImgUpload(
            @ApiParam("文件上传") @RequestPart("multipartFile") MultipartFile multipartFile,
            HttpServletRequest request
    ) {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String originalFilename = multipartFile.getOriginalFilename();
        int i = originalFilename.lastIndexOf(".");
        String newFilename = uuid.concat(originalFilename.substring(i));
        //保存图片，一般第三方图片服务器
//        request.getServletContext().getRealPath("public/upload/");//springboot用的内置的tomcat 就不是真实的target路径
        String portraitPath = "E:\\Code\\java_study\\projects\\zhxy\\target\\classes\\public\\upload\\".concat(newFilename);
        try {
            multipartFile.transferTo(new File(portraitPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //将图片路径返回
        String path = "upload/".concat(newFilename);
        return Result.ok(path);
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/getInfo")
    public Result getInfoByToken(@ApiParam("token口令")@RequestHeader("token") String token) {
        //判断token 是否过期
        boolean expiration = JwtHelper.isExpiration(token);
        if (expiration) {
            return Result.build(null, ResultCodeEnum.TOKEN_ERROR);
        }
        //没有过期 从token 中解析出 用户id 和用户类型
        Long userId = JwtHelper.getUserId(token);
        Integer userType = JwtHelper.getUserType(token);

        Map<String, Object> map = new LinkedHashMap<>();
        switch (userType) {
            case 1:
                Admin admin = adminService.getById(userId);
                map.put("userType", 1);
                map.put("user", admin);
                break;
            case 2:
                Student student = studentService.getById(userId);
                map.put("userType", 2);
                map.put("user", student);
                break;
            case 3:
                Teacher teacher = teacherService.getById(userId);
                map.put("userType", 3);
                map.put("user", teacher);
                break;
        }
        return Result.ok(map);
    }

    @ApiOperation("登录")
    @PostMapping("/login")
    public Result login(@RequestBody LoginForm loginForm, HttpServletRequest request) {
        //1、校验验证码
        HttpSession session = request.getSession();
        String sessionVerifyCode = (String) session.getAttribute("verifiCode");
        String loginVerifyCode = loginForm.getVerifiCode();
        if ("".equals(sessionVerifyCode) || null == sessionVerifyCode) {
            return Result.fail().message("验证码失效，请刷新重试。");
        }
        if (!loginVerifyCode.equalsIgnoreCase(sessionVerifyCode)) {
            return Result.fail().message("验证码错误，请重新输入。");
        }
        //2、从session域中移除验证码（防止恶意利用)
        session.removeAttribute("verifiCode");
        //3、查询数据库看用户名密码是否正确（根据不同用户类型)

        //准备一个map 用于放响应的数据
        Map<String, Object> map = new HashMap<>();
        switch (loginForm.getUserType()) {
            case 1:
                try {
                    Admin admin = adminService.login(loginForm);
                    if (null != admin) {
                        //                    将用户id 和 类型 生成一段密文 以token 名称向客户端反馈
                        map.put("token", JwtHelper.createToken(admin.getId().longValue(), 1));
                    } else {
                        throw new RuntimeException("用户名或密码错误！");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }
            case 2:
                try {
                    Student student = studentService.login(loginForm);
                    if (null != student) {
                        //                    将用户id 和 类型 生成一段密文 以token 名称向客户端反馈
                        map.put("token", JwtHelper.createToken(student.getId().longValue(), 2));
                    } else {
                        throw new RuntimeException("用户名或密码错误！");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }
            case 3:
                try {
                    Teacher teacher = teacherService.login(loginForm);
                    if (null != teacher) {
                        //                    将用户id 和 类型 生成一段密文 以token 名称向客户端反馈
                        map.put("token", JwtHelper.createToken(teacher.getId().longValue(), 3));
                    } else {
                        throw new RuntimeException("用户名或密码错误！");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }
        }

        return Result.fail().message("查无此用户！");
    }

    @ApiOperation("获取登录验证码")
    @GetMapping("/getVerifiCodeImage")
    public void getVerifiCodeImage(HttpServletRequest request, HttpServletResponse response) {
//        1、获取验证码图片
        BufferedImage verifiCodeImage = CreateVerifiCodeImage.getVerifiCodeImage();
//        2、获取验证码文本
        String verifiCode = new String(CreateVerifiCodeImage.getVerifiCode());
//        3、将验证码文本存入session域 方便再次验证
        HttpSession session = request.getSession();
        session.setAttribute("verifiCode", verifiCode);
//        4、通过io流将验证码图片返回前端
        try {
            ImageIO.write(verifiCodeImage, "JPEG", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
